from datetime import datetime, date

from django.db.models import F
from rest_framework import viewsets, mixins
from rest_framework.decorators import action
from rest_framework.permissions import IsAuthenticated
from rest_framework.views import Response, status

from apps.common.account.models import AccountRoles
from apps.survey_system.question.models import Module
from apps.survey_system.survey.models import Survey, SurveyQuestionCategory, SurveyQuestion, SurveyAccount, SurveyAnswer


class IndexViewSet(mixins.ListModelMixin, viewsets.GenericViewSet):
    permission_classes = [IsAuthenticated]

    def list(self, request, *args, **kwargs):
        """
        获取当前课程数、测评数，未开始，进行中，已结束
        {
            "课程数": 3,
            "批判性思维": 1,
            "心理健康": 12,
            "审美素养": 2,
            "测评数": 15,
            "未开始": 0,
            "进行中": 0,
            "已结束": 15
        }
        {
         'id'：1
         'name':
         'child':[
             {
              'id':
              'name':
             }
          ]
        }
        """
        username_ls = []
        faculty_ls = []
        major_ls = []
        class_ls = []
        use_people_count = 0
        use_faculty_count = 0
        use_major_count = 0
        use_class_count = 0

        if request.user.is_admin():
            module_ids = Module.objects.all().values_list('id', flat=True)
        else:
            role_qs = AccountRoles.objects.filter(account_id=request.user.id).values_list('role__codename', flat=True)
            if not role_qs:
                return Response({'message': '无权限查看，请联系系统管理员！'}, status=status.HTTP_400_BAD_REQUEST)
            module_codename = []
            for i in role_qs:
                str_ls = i.split('_')
                module_codename.append(str_ls[0])
            module_ids = Module.objects.filter(codename__in=module_codename).values_list('id', flat=True)


        survey_account_qs = SurveyAccount.objects.filter(status__in=[1, 2])\
            .values('username', 'faculty_code', 'major_code', 'class_code')

        for qs in survey_account_qs:
            if qs['username'] not in username_ls:
                username_ls.append(qs['username'])
                use_people_count += 1

            if qs['faculty_code'] not in faculty_ls:
                faculty_ls.append(qs['faculty_code'])
                use_faculty_count += 1

            if qs['major_code'] not in major_ls:
                major_ls.append(qs['major_code'])
                use_major_count += 1

            if qs['class_code'] not in class_ls:
                class_ls.append(qs['class_code'])
                use_class_count += 1

        use_system_dict = {
            '使用系统人数': use_people_count,
            '使用系统学院数量': use_faculty_count,
            '使用系统专业数量': use_major_count,
            '使用系统班级数量': use_class_count
        }

        today = datetime.now()
        survey_dict = {
            '总测评数': 0,
            '未开始': 0,
            '进行中': 0,
            '已结束': 0
        }
        survey_qs = Survey.objects.filter(module_id__in=module_ids, is_active=True)\
            .values('id', 'name', 'start_time', 'end_time', 'module_id', module_name=F('module__name'))
        module_dict = {}
        for qs in survey_qs:
            if qs['module_id'] not in module_dict.keys():
                module_dict[qs['module_id']] = {
                    'id': qs['module_id'],
                    'module_name': qs['module_name'],
                    'child': []
                }
            survey_dict['总测评数'] += 1
            if qs['start_time'] > today:
                survey_dict['未开始'] += 1
            elif qs['end_time'] < today:
                survey_dict['已结束'] += 1
                survey_dict1 = {'id': qs['id'], 'name': qs['name']}
                module_dict[qs['module_id']]['child'].append(survey_dict1)
            else:
                survey_dict['进行中'] += 1

        res_data = {**use_system_dict,  **survey_dict}
        data ={'res_data': res_data}
        return Response(data, status=status.HTTP_200_OK)

    # 每个学院的每个维度的分析
    @action(methods=['get'], detail=False, url_path='survey_faculty_avg_analysis')
    def get_survey_faculty_avg_analysis(self, request, pk=None):
        survey_id = request.query_params.get('survey_id', None)
        if not survey_id:
            return Response({'message': '缺少参数'}, status=status.HTTP_400_BAD_REQUEST)

        # 问卷问题个数
        category_qs = SurveyQuestionCategory.objects.filter(survey_id=survey_id).values('id', 'category_name')
        category_ids = []
        category_dict = {}
        category_qt_count = {}

        category_score_dict = {}  # 保存每个维度的分数

        for cate in category_qs:
            category_ids.append(cate['id'])
            category_dict[cate['id']] = cate['category_name']
            category_qt_count[cate['id']] = 0
            category_score_dict[cate['id']] = 0

        question_qs = SurveyQuestion.objects.filter(survey_qs_cate_id__in=category_ids) \
            .values('id', 'survey_qs_cate_id', 'name', 'score')

        question_count = 0  # 题目数
        question_cate_dict = {}
        survey_all_score = 0  # 测评的总分
        for qt in question_qs:
            question_count += 1
            question_cate_dict[qt['id']] = qt['survey_qs_cate_id']
            category_qt_count[qt['survey_qs_cate_id']] += 1
            survey_all_score += qt['score']

        # 成绩发布计算区间
        score_step = survey_all_score // 5
        score_section = []
        section_people = {}
        left_data = 0
        for i in range(5):
            if i < 4:
                section = [left_data, left_data + score_step]
            else:
                section = [left_data, survey_all_score]
            left_data += score_step
            score_section.append(section)

            section_people[i] = 0

        faculty_qs = SurveyAccount.objects.filter(survey_id=survey_id).values('faculty_code', 'faculty_title').distinct()
        faculty_dict = {}
        faculty_score = {}
        for faculty in faculty_qs:
            faculty_dict[faculty['faculty_code']] = faculty
            faculty_score[faculty['faculty_code']] = {}
            faculty_score[faculty['faculty_code']]['all'] = {}
            faculty_score[faculty['faculty_code']]['all']['score'] = 0
            faculty_score[faculty['faculty_code']]['all']['people'] = 0
            for cate_id in category_ids:
                faculty_score[faculty['faculty_code']][cate_id] = {}
                faculty_score[faculty['faculty_code']][cate_id]['score'] = 0

        # 填写对象
        survey_account = SurveyAccount.objects.filter(survey_id=survey_id, status__in=[1, 2]).values()

        survey_account_dict = {}
        survey_account_ids = []

        survey_account_score = {}  # 保存每个人的得分
        all_score = 0  # 保存所有人的总得分

        survey_account_count = len(survey_account)

        for qs in survey_account:
            survey_account_ids.append(qs['id'])
            survey_account_dict[qs['id']] = {}
            survey_account_dict[qs['id']]['all_score'] = 0
            survey_account_dict[qs['id']]['faculty_code'] = qs['faculty_code']

            survey_account_score[qs['id']] = 0

        survey_answer_qs = SurveyAnswer.objects.filter(survey_account_id__in=survey_account_ids) \
            .values('survey_account_id', 'score', 'question_id', 'answer_id_lst')

        for qs in survey_answer_qs:
            survey_account_dict[qs['survey_account_id']]['all_score'] += qs['score']

            cate_id = question_cate_dict[qs['question_id']]
            if cate_id not in survey_account_dict[qs['survey_account_id']]:
                survey_account_dict[qs['survey_account_id']][cate_id] = 0
            survey_account_dict[qs['survey_account_id']][cate_id] += qs['score']

            category_score_dict[cate_id] += qs['score']

            survey_account_score[qs['survey_account_id']] += qs['score']
            all_score += qs['score']

        # 计算成绩发布
        for key in survey_account_score.keys():
            for i in range(5):
                if survey_account_score[key] >= score_section[i][0] and survey_account_score[key] < score_section[i][1]:
                    section_people[i] += 1
                    break

        yht_avg = []
        for i in range(5):
            name = str(score_section[i][0]) + '分-' + str(score_section[i][1]) + '分'
            yht_dict = {
                'value': section_people[i],
                'name': name
            }
            yht_avg.append(yht_dict)

        yht_avg_score = round(all_score/survey_account_count, 1) if survey_account_count != 0 else 0

        yht_data = {
            'data': yht_avg,
            'title': '测评分数的分布情况',
            'name': f'平均分{yht_avg_score}'
        }

        for qs in survey_account:
            account_dict = survey_account_dict[qs['id']]
            faculty_code = qs['faculty_code']
            faculty_score[faculty_code]['all']['score'] += account_dict['all_score']
            faculty_score[faculty_code]['all']['people'] += 1
            for cate_id in category_ids:
                faculty_score[faculty_code][cate_id]['score'] += account_dict[cate_id]

        cate_ls = ['选项']
        cate_indicator = []
        cate_score_avg_data = []
        for cate_id in category_ids:
            cate_ls.append(category_dict[cate_id])

            # 计算每个维度的总均分
            all_cate_score = category_score_dict[cate_id]
            cate_question = category_qt_count[cate_id]
            if all_cate_score != 0 and survey_account_count != 0:
                cate_all_score_avg = round(all_cate_score / (survey_account_count * cate_question), 1)
                cate_score_avg_data.append(cate_all_score_avg)
                cate_indicator.append({'text': category_dict[cate_id], 'max': 5})

        # 雷达图数据
        ldt_data = {
            'indicator': cate_indicator,
            'data': [{'value': cate_score_avg_data, 'name': '各个维度的平均分统计'}]
        }

        cate_avg = [cate_ls]
        for key in faculty_score.keys():
            faculty_name = faculty_dict[key]['faculty_title']
            all_people = faculty_score[key]['all']['people']
            cate_data = [faculty_name]
            flag = 0
            for cate_id in category_ids:
                cate_score = faculty_score[key][cate_id]['score']
                cate_question = category_qt_count[cate_id]
                if all_people:
                    cate_score_avg = round(cate_score / (all_people * cate_question), 1)
                else:
                    cate_score_avg = 0
                if cate_score_avg != 0:
                    flag = 1
                cate_data.append(cate_score_avg)
            if flag != 0:
                cate_avg.append(cate_data)

        # 柱状图数据
        ztt_data = {
                      'id': 'cate',
                      'activeName': 'cate-barchart',
                      'name': '各个维度的均分',
                      'data': cate_avg,
                      'title': '各个学院各个维度的均分分析'
                   }

        res_data = {'data': ztt_data, 'title': "各个学院各个维度的均分分析", 'ldt_data': ldt_data, 'yht_data': yht_data}
        return Response(res_data, status=status.HTTP_200_OK)